﻿CREATE PROCEDURE [dbo].[PartiesUpdate]
(
	@RetailPrice decimal(19, 2),
	@BarCode char(12),
	@Blocked bit,
	@Note varchar(250),
	@MD datetime,
	@MW varchar(50),
	@Original_Id int,
	@Original_MD datetime
)
AS
/*Основное назначение - редактирование Note, Blocked и BarCode
Остальные поля редактировать только в случае крайней необходимости
*/
DECLARE @strMsg nvarchar(500), @intRet int, @intErrCode int
DECLARE @RestQntty int, @orgRetailPrice decimal(19, 2), @intPartyTrancCount int

SET NOCOUNT ON

IF (@RetailPrice Is Null) OR (@BarCode Is Null) --OR (@RestQntty Is Null) (@GoodsId Is Null) OR 
OR (@Original_Id Is Null) OR (@Original_MD Is Null)
BEGIN
	SELECT @intErrCode = 1, @strMsg = 'Неправильные параметры в вызове процедуры ' + Object_Name(@@Procid) + ' !'
	RAISERROR (@strMsg, 11, @intErrCode)
	RETURN @intErrCode
END

SELECT @orgRetailPrice = RetailPrice FROM [CD].[Parties] WHERE Id = @Original_Id AND MD = @Original_MD
IF (@@rowcount <> 1)
BEGIN
	SELECT @intErrCode = 2, 
	@strMsg = 'Данные изменены после последнего запроса!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

IF (@RetailPrice < 0.01)
BEGIN
	SELECT @intErrCode = 3, 
	@strMsg = 'Цена должна быть больше нуля!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

EXEC [dbo].[ProcessStatistic] @Note OUTPUT, @MD OUTPUT, @MW OUTPUT

BEGIN TRAN
--расчет динамического остатка
SELECT @RestQntty = Sum(Qntty), @intPartyTrancCount = count(*) FROM CA.GoodsDocLines WITH (HOLDLOCK TABLOCKX)
WHERE PartyId = @Original_Id
GROUP BY PartyId 

IF ( @RetailPrice <> @orgRetailPrice ) --изменена цена
BEGIN
	IF @intPartyTrancCount <> 1
	BEGIN
		IF @@trancount > 0 ROLLBACK TRAN
		SELECT @intErrCode = 4, 
		@strMsg = 'По партии с идентификатором ' + cast(@Original_Id as varchar(20)) + ' было товародвижение, поэтому цена менять нельзя!'
		RAISERROR (@strMsg, 11, 1)
		RETURN @intErrCode
	END
--обновляем сумму проводки
	UPDATE CA.GoodsDocLines SET RetailSum = @RetailPrice * Qntty WHERE PartyId = @Original_Id

END

	SET NOCOUNT OFF;
UPDATE [CD].[Parties] SET [RetailPrice] = @RetailPrice,
[BarCode] = @BarCode, [Blocked] = @Blocked, 
[RestQntty] = @RestQntty, 
[Note] = @Note, [MD] = @MD, [MW] = @MW 
WHERE Id = @Original_Id;
	
COMMIT TRAN

SELECT Id, DocId, GoodsId, RetailPrice, BarCode, InputLineId, Blocked, RestQntty, 
Note, MD, MW FROM CD.Parties WHERE (Id = @Original_Id)

RETURN 0